package me.zxk.qwert_poetry.dto.response;

import lombok.Data;
import me.zxk.qwert_poetry.dao.Author;
import me.zxk.qwert_poetry.dao.Collection;
import me.zxk.qwert_poetry.dao.Poem;
import org.apache.catalina.User;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Data
public class CollectionResponseDTO {
    @Data
    static class PoemDTO {
        private Integer id;
        private String title;
        private Author author;

        public static PoemDTO fromEntity(Poem p) {
            PoemDTO dto = new PoemDTO();
            dto.setId(p.getId());
            dto.setTitle(p.getTitle());
            dto.setAuthor(p.getAuthor());
            return dto;
        }
    }

    @Data
    static class UserDTO {
        private Integer id;
        private String nickname;
        private String email;
    }

    private Integer id;
    private UserDTO user;
    private String creationTime;
    private String title;
    private String desc;
    private List<PoemDTO> poems;

    public static CollectionResponseDTO fromEntity(Collection c) {
        CollectionResponseDTO dto = new CollectionResponseDTO();
        dto.setId(c.getId());
        dto.setUser(new UserDTO() {{
            setId(c.getUser().getId());
            setNickname(c.getUser().getNickname());
            setEmail(c.getUser().getEmail());
        }});

        TimeZone tz = TimeZone.getTimeZone("UTC");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
        df.setTimeZone(tz);
        dto.setCreationTime(df.format(new Date(c.getCreationTime().getTime())));
        dto.setTitle(c.getTitle());
        dto.setDesc(c.getDesc());
        if (c.getPoems() != null)
            dto.setPoems(c.getPoems().stream().map(PoemDTO::fromEntity).toList());
        return dto;
    }
}
